import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ValidationPipe } from '@nestjs/common'
import { HttpExceptionFilter } from './common/filters/http-exception.filter'
import { ConfigService } from '@nestjs/config'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'

async function bootstrap() {
    const app = await NestFactory.create(AppModule)
    const configService = app.get(ConfigService)

    // 配置 CORS
    app.enableCors({
        origin: configService.get('FRONTEND_URL', 'http://localhost:5173'),
        methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
        credentials: true,
    })

    // 配置 Swagger
    const config = new DocumentBuilder()
        .setTitle('AI Drawing API')
        .setDescription('The AI Drawing API description')
        .setVersion('1.0')
        .addBearerAuth()
        .build()
    const document = SwaggerModule.createDocument(app, config)
    SwaggerModule.setup('api/docs', app, document)

    // 全局错误过滤器
    app.useGlobalFilters(new HttpExceptionFilter())

    // 全局验证管道
    app.useGlobalPipes(new ValidationPipe({
        transform: true,
        whitelist: true,
        forbidNonWhitelisted: true,
    }))

    // 从环境变量获取端口
    const port = configService.get('PORT', 3000)
    await app.listen(port)
    console.log(`Application is running on: http://localhost:${port}`)
    console.log(`Swagger documentation is available at: http://localhost:${port}/api/docs`)
}

bootstrap().catch(err => {
    console.error('Failed to start application:', err)
    process.exit(1)
})